<!-- src/components/NoticeModal.vue -->
<!-- 第三步：创建公告模态框组件 -->
<template>
  <div class="modal-overlay" @click.self="close">
    <div class="modal-content">
      <div class="modal-header">
        <h3>{{ isEditing ? '编辑公告' : '发布公告' }}</h3>
        <button class="close-btn" @click="close">×</button>
      </div>

      <form @submit.prevent="submitForm">
        <div class="form-group">
          <label>标题 *</label>
          <input 
            v-model="formData.title" 
            required 
            placeholder="输入公告标题"
            class="form-control"
          >
        </div>

        <div class="form-group">
          <label>内容 *</label>
          <textarea 
            v-model="formData.content" 
            required 
            rows="6" 
            placeholder="输入公告内容"
            class="form-control"
          ></textarea>
        </div>

        <div class="form-group">
          <label>目标群体</label>
          <div class="target-group">
            <label v-for="group in targetGroups" :key="group.value" class="checkbox-label">
              <input 
                type="checkbox" 
                v-model="formData.targetGroup" 
                :value="group.value"
              >
              {{ group.label }}
            </label>
          </div>
        </div>

        <div class="form-group">
          <label>过期时间</label>
          <input 
            v-model="formData.expireTime" 
            type="datetime-local" 
            class="form-control"
          >
        </div>

        <div class="modal-actions">
          <button type="button" class="btn-cancel" @click="close">取消</button>
          <button type="submit" class="btn-submit" :disabled="loading">
            {{ loading ? '保存中...' : (isEditing ? '更新' : '发布') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>
<script>
import { ref, computed, watch } from 'vue';
import { noticeApi } from '@/api/notice';

export default {
  name: 'NoticeModal',
  props: {
    notice: {
      type: Object,
      default: null
    }
  },
  emits: ['close', 'saved'],
  setup(props, { emit }) {
    const loading = ref(false);
    const isEditing = computed(() => !!props.notice);
    
    const targetGroups = ref([
      { value: 'admin', label: '管理员' },
      { value: 'teacher', label: '教师' },
      { value: 'student', label: '学生' }
    ]);
    
    const formData = ref({
      title: '',
      content: '',
      targetGroup: [],
      expireTime: ''
    });

    // 先定义 resetForm 函数
    const resetForm = () => {
      formData.value = {
        title: '',
        content: '',
        targetGroup: [],
        expireTime: ''
      };
    };

    // 使用 watch 监听 props 变化
    watch(() => props.notice, (newNotice) => {
      if (newNotice) {
        formData.value = {
          title: newNotice.title,
          content: newNotice.content,
          targetGroup: newNotice.targetGroup || [],
          expireTime: newNotice.expireTime || ''
        };
      } else {
        resetForm(); // 现在可以安全使用
      }
    }, { immediate: true });

    const close = () => {
      emit('close');
    };

    const submitForm = async () => {
      // 表单验证
      if (!formData.value.title.trim()) {
        alert('请输入公告标题');
        return;
      }
      if (!formData.value.content.trim()) {
        alert('请输入公告内容');
        return;
      }

      loading.value = true;
      try {
        if (isEditing.value) {
          // 编辑公告
          await noticeApi.updateNotice(props.notice.id, formData.value);
        } else {
          // 发布公告
          await noticeApi.publishNotice(formData.value);
        }
        
        emit('saved');
      } catch (error) {
        console.error('保存公告失败:', error);
        const errorMsg = error.response?.data?.message || error.message || '操作失败';
        alert(`操作失败: ${errorMsg}`);
      } finally {
        loading.value = false;
      }
    };

    return {
      formData,
      targetGroups,
      isEditing,
      loading,
      close,
      submitForm
    };
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 600px;
  max-width: 90vw;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #666;
}

.form-group {
  margin-bottom: 20px;
  padding: 0 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-control {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-control:focus {
  outline: none;
  border-color: #3498db;
}

.target-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #eee;
}

.btn-cancel, .btn-submit {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-cancel {
  background: #f5f5f5;
  color: #666;
}

.btn-submit {
  background: #3498db;
  color: white;
}

.btn-submit:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.btn-submit:hover:not(:disabled) {
  background: #2980b9;
}

@media (max-width: 768px) {
  .modal-content {
    width: 90vw;
  }
}
</style>